import sys
import getopt
import os.path
import chardet
import shutil

version = "0.1.0"


def ScanFiles(directory):
    #Get all file in directory and subdirectory.
    filelist = []
    allObjects = [
        directory + os.sep + filename for filename in os.listdir(directory)]
    for m in allObjects:
        if os.path.isfile(m):
            filelist.append(m)
        elif os.path.isdir(m):
            filelist.extend(ScanFiles(m))
        else:
            pass
    return filelist


def print_usage():
    # Output help message.
    print('econvr  ', version, sep='')
    print('Detect and convert encoding of text.')
    print(
        'usage:econvr <target_encoding> [-f|--file <file1>,<file2>...][-d|--dir <dir1>,<dir2>...][-s|--simple][-h|--help]')
    print('-f,--file\tFollowed a file list which need to be convert.List using comma separated.')
    print('-d,--dir\tFollowed a directory list which need to be convert.List using comma separated.')
    print('-s,--simple\tDetect the encoding only.Don\'t run converter.The output format is same as chardet\'s.')
    print('-h,--help\tPrint help message.')

error_exit_code = 1
file_paths = []
is_only_detect = False

try:
    opts, args = getopt.gnu_getopt(sys.argv[1:], 'd:f:hs', [
                                   'file=', 'dir=', 'simple', 'help'])
    if args:
        target_encoding = args[0]
except Exception:
    print('Argument parse error!')
    sys.exit(error_exit_code)

#Parse arguments.
for opt, val in opts:
    if opt in ('-f', '--file'):
        for file_path in val.split(','):
            # import pdb
            # pdb.set_trace()
            if not os.path.isfile(file_path):
                print('{0} is not a file or doesn\'t exist!'.format(file_path))
            else:
                file_paths.append(file_path)
    elif opt in ('-d', '--dir'):
        for directory in val.split(','):
            if os.path.isdir(directory):
                file_paths.extend(ScanFiles(directory))
            else:
                print('{0} is not a dir or doesn\'t exist!'.format(directory))
    elif opt in ('-s', '--simple'):
        is_only_detect = True
    else:
        print_usage()
        sys.exit()

for file_path in file_paths:
    temp_path = file_path + '.tmp'
    try:
        raw_context = ''
        detect_result = {}
        with open(file_path, mode='rb') as raw_file:
            raw_context = raw_file.read()
            detect_result = chardet.detect(raw_context)
        if is_only_detect:
            print('{0}: {1} with confidence {2}'.format(
                file_path, detect_result['encoding'], detect_result['confidence']))
        else:
            print('Converting {0}: {1}...'.format(
                file_path, detect_result['encoding']), end='')
            with open(temp_path, mode='wb') as temp_file:
                temp_file.write(raw_context.decode(
                    detect_result['encoding']).encode(target_encoding))
            os.remove(file_path)
            shutil.move(temp_path, file_path)
            print('done!')
    except Exception as ex:
        print(ex)
    finally:
        if os.path.exists(temp_path):
            os.remove(temp_path)
